﻿using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Reflection;

namespace EntLibSample.DALCommon
{
    public class DataMapper
    {

        public static List<TType> MapDataTableToObjectList<TType>(DataTable dt) where TType : new()
        {
            DataColumnCollection columns = dt.Columns;
            int iColumnCount = columns.Count;
            TType ttype = new TType();
            Type elementType;
            elementType = ttype.GetType();
            PropertyInfo[] publicProperties = elementType.GetProperties();
            List<TType> result = new List<TType>();
            //if (publicProperties.Length == iColumnCount)
            //{
            foreach (DataRow currentRow in dt.Rows)
            {
                for (int i = 0; i < iColumnCount; i++)
                {
                    for (int j = 0; j < publicProperties.Length; j++)
                    {
                        if (columns[i].ColumnName.ToUpper() == publicProperties[j].Name.ToUpper())
                        {
                            if (currentRow[i] != DBNull.Value)
                            {
                                publicProperties[j].SetValue(ttype, currentRow[i], null);
                            }
                            break;
                        }
                    }
                }
                result.Add(ttype);
                ttype = new TType();
            }
            //}
            //else
            //{
            //    result = null;
            //}
            return result;
        }

        public static TType MapDataTableToSingleRow<TType>(DataTable dt) where TType : new()
        {
            DataColumnCollection columns = dt.Columns;
            int iColumnCount = columns.Count;
            TType ttype = new TType();
            Type elementType;
            elementType = ttype.GetType();
            PropertyInfo[] publicProperties = elementType.GetProperties();
            //if (publicProperties.Length == iColumnCount)
            //{
            if (dt.Rows.Count > 0)
            {
                DataRow currentRow = dt.Rows[0];
                for (int i = 0; i < iColumnCount; i++)
                {
                    for (int j = 0; j < publicProperties.Length; j++)
                    {
                        if (columns[i].ColumnName.ToUpper() == publicProperties[j].Name.ToUpper())
                        {
                            if (currentRow[i] != DBNull.Value)
                            {
                                publicProperties[j].SetValue(ttype, currentRow[i], null);
                            }
                            break;
                        }
                    }
                }
            }
            //}
            return ttype;
        }
    }
}